<template>
  <a-modal width="60%" :visible="open" @cancel="onClose" @ok="submitForm" :confirmLoading="submitLoading" :maskClosable="false">
      <a-spin :spinning="spinning" size="large">
        <a-divider orientation="left">
          <b>{{ formTitle }}</b>
        </a-divider>
        <a-form-model ref="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" :model="form" :rules="rules">
          <a-form-model-item label="选择会员卡" prop="tcardId">
            <a-select placeholder="请选择会员卡" v-model="form.tcardId" style="width: 100%" allow-clear @change="cardChange" :disabled="!showFlag">
              <a-select-option v-for="(d, index) in cardList" :key="index" :value="d.id">{{ d.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="会员卡信息">
            <a-descriptions :column="1">
              <a-descriptions-item label="卡类型">
                {{ cardInfo.cardTypeName }}
              </a-descriptions-item>
              <template v-if="cardInfo.cardType != 3">
                <a-descriptions-item label="总次数/总时长" v-if="cardInfo.count">
                  {{ cardInfo.count }}
                </a-descriptions-item>
                <a-descriptions-item label="有效期">
                  {{ cardInfo.desc }}
                </a-descriptions-item>
              </template>
            </a-descriptions>
          </a-form-model-item>


          <a-form-model-item v-if="cardInfo.cardType == 3 || this.form.cardType == 3" label="私教卡数量" prop="cardCount">
            <a-input v-model="form.cardCount" />
          </a-form-model-item>
          <a-form-model-item label="有效期" prop="time" v-if="cardInfo.cardType == 3 || this.form.cardType == 3">
            <a-input v-model="form.time" placeholder="请输入有效期" />
            <a-radio-group v-model="form.timeType" button-style="solid">
              <a-radio-button v-for="(d, index) in timeTypeOptions" :key="index" :value="d.dictValue">{{ d.dictLabel }}</a-radio-button>
            </a-radio-group>
          </a-form-model-item>

          <a-form-model-item label="收费方式" prop="charge">
            <a-select v-model="form.charge" placeholder="请选择收费方式">
              <a-select-option v-for="(d, index) in chargeList" :key="index" :value="d.dictValue">{{
                d.dictLabel
              }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="来源" prop="source">
            <a-select v-model="source" placeholder="请选择来源">
              <a-select-option v-for="(d, index) in sourceList" :key="index" :value="d.dictValue">{{
                d.dictLabel
              }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="收费金额" prop="chargeAmount">
            <a-input v-model="form.chargeAmount" placeholder="请选择收费金额" :disabled="!showFlag || balanceFlag"/>
          </a-form-model-item>
          <a-form-model-item label="收费时间" prop="chargeTime">
            <a-date-picker
              v-model="form.chargeTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :style="{ width: '100%' }"
              placeholder="请选择收费时间"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item label="是否选择保险" prop="insure">
            <a-radio-group v-model="form.insure">
              <a-radio value="A">是</a-radio>
              <a-radio value="B">否</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="设置赠品">
            <template v-for="item in giveInfo">
              <a-checkable-tag @change="checkableTag(item)">
                {{ item.name }}
              </a-checkable-tag>
            </template>
          </a-form-model-item>
          <a-form-model-item label="设置规格" v-if="standFlag">
            <template v-for="item in standardList">
              <a-checkable-tag @change="addChoose(item)">
                {{ item.value }}
              </a-checkable-tag>
            </template>
          </a-form-model-item>
          <a-form-model-item label="所选规格">
            <a-tag v-for="(item, index) in choseList" :key="item" @close="closeTag(index)" :closable="true">
                {{ item.name }}
              </a-tag>
          </a-form-model-item>
          <a-form-model-item label="业绩归属校区" prop="ascription">
            <a-tree-select
              :disabled="!showFlag"
              v-model="form.ascription"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="treeData"
              placeholder="请选择业绩归属校区"
              :replaceFields="{ children: 'children', title: 'label', key: 'id', value: 'id' }"
              tree-default-expand-all
            >
            </a-tree-select>
          </a-form-model-item>
          <a-form-model-item label="业绩归属人" prop="ascriptionSale">
            <a-select placeholder="请选择业绩归属人" v-model="form.ascriptionSale" :disabled="ascriptionSaleDisabled" :filterOption="hanleFilter" showSearch>
              <a-select-option v-for="(d, index) in dataSource" :key="index" :value="d.id">{{ d.name }}</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="协议编号">
            <a-input v-model="form.agreement" placeholder="请填写协议编号"></a-input>
          </a-form-model-item>
          <a-form-model-item label="收据编号">
            <a-input v-model="form.chargeNum" placeholder="请填写收据编号"></a-input>
          </a-form-model-item>
          <a-form-model-item label="备注">
            <a-textarea v-model="form.remark"></a-textarea>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
  </a-modal>
  
  
</template>

<script>
import { getStudentCard, addStudentCard, updateStudentCard } from '@/api/manager/studentCard'
import { getOwnerGroup } from '@/api/manager/student'
import { treeselect } from '@/api/system/dept'
import { getGiveList } from '@/api/manager/giveaway'
import { getCardList } from '@/api/manager/card'
import moment from 'moment'
import storage from'store'


export default {
  name: 'CreateForm',
  props: {},
  components: {},
  data() {
    return {
      spinning:false,
      currentDeptId:null,
      showFlag:false,
      privateForm:{},
      source: '',
      dataSource: [],
      value: null,
      treeData: [],
      choseList: [],
      standardList: [],
      standName: null,
      standFlag: false,
      giveInfo: [],
      cardInfo: {
        cardTypeName: null,
        count: null,
        desc: null,
        flag: true,
        cardType:null,
      },
      cardList: [],
      submitLoading: false,
      formTitle: '',
      chargeList: [],
      sourceList: [],
      ascriptionSaleDisabled:false,
      // 表单参数
      form: {
        timeTypeOptions:[],
        id: null,
        studentId: null,
        cardId: null,
        cardNo: null,
        count: null,
        giveCount: null,
        startTime: null,
        endTime: null,
        give: null,
        ascription: null,
        ascriptionSale: null,
        chargeAmount: null,
        charge: null,
        chargeNum: null,
        agreement: null,
        status: '0',
        type: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      },
      // 1增加,2修改
      formType: 1,
      open: false,
      rules: {
        time:[{ required: true, message: '私教卡时间不能为空', trigger: 'blur' }],
        cardCount: [{ required: true, message: '私教卡数量不能为空', trigger: 'blur' }],
        privateDate: [{ required: true, message: '私教卡开始截至时间不能为空', trigger: 'blur' }],
        tcardId: [{ required: true, message: '卡包编号不能为空', trigger: 'blur' }],
        insure: [{ required: true, message: '是否选择保险不能为空', trigger: 'blur' }],
        chargeTime: [{ required: true, message: '收费时间不可为空', trigger: 'blur' }],

        startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],

        endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],

        ascription: [{ required: true, message: '业绩归属校区不能为空', trigger: 'blur' }],

        ascriptionSale: [{ required: true, message: '业绩归属人不能为空', trigger: 'blur' }],

        chargeAmount: [{ required: true, message: '收费金额不能为空', trigger: 'blur' }],

        charge: [{ required: true, message: '收费方式不能为空', trigger: 'blur' }],

        source: [{ required: true, message: '来源不能为空', trigger: 'blur' }],

        chargeNum: [{ required: true, message: '收据编号不能为空', trigger: 'blur' }],

        agreement: [{ required: true, message: '协议编号不能为空', trigger: 'blur' }],
      },
    }
  },
  filters: {},
  created() {
    this.getDicts('t_charge_type').then((response) => {
      this.chargeList = response.data
    })

    this.getDicts('business_source').then((response) => {
      this.sourceList = response.data
    })

    this.getDicts('time_type').then(response => {
      this.timeTypeOptions = response.data
    })

    this.giveList()

    this.currentDeptId = storage.get("deptId");
  },
  computed: {},
  watch: {},
  mounted() {},
  methods: {
    hanleFilter(input, option){
      return (
        option.componentOptions.children[0].text.indexOf(input) >= 0
      );
    },
    getOwner() {
      getOwnerGroup().then((resp) => {
        this.dataSource = resp.data
      })
    },
    changeValue(value, option) {
      this.form.ascriptionSale = option.data.key
    },
    getTreeSelect() {
      treeselect().then((resp) => {
        this.treeData = resp.data
      })
    },
    closeTag(index) {
      this.choseList.splice(index,1)
      if(this.choseList.length == 0){
        this.form.give = '';
        this.choseList = [];
      }
    },
    addChoose(item) {
      if(this.choseList == null){
        this.choseList = [];
      }
      this.choseList.push({
        name: this.standName + '-' + item.value,
      })
    },
    checkableTag(item) {
      if(this.choseList == null){
        this.choseList = []
      }
      if (item.typeList != null && item.typeList.length > 0) {
        this.standardList = item.typeList
        this.standName = item.name
        this.standFlag = true
      } else {
        this.standFlag = false
        this.choseList.push({
          name: item.name,
        })
      }
    },
    giveList() {
      getGiveList().then((resp) => {
        this.giveInfo = resp.data
      })
    },
    cardChange(value, option) {
      let data = this.cardList[option.key]
      this.cardInfo.cardTypeName = data.cardTypeName
      this.cardInfo.cardType= data.cardType
      this.cardInfo.count = data.count
      this.cardInfo.desc = data.desc
      if (data.time == null) {
        this.cardInfo.flag = false
      } else if (data.cardType == 2) {
        this.cardInfo.flag = false
      } else {
        this.cardInfo.flag = true
      }

      //短期时间卡
      if(data.cardType == 4){
        this.form.startTime = data.start;
        this.form.endTime = data.end;
      }

    },
    cardSelect() {
      getCardList().then((resp) => {
        this.cardList = resp.data
      })
    },
    onClose() {
      this.open = false
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      balanceFlag:false,
      this.formType = 1
      this.choseList = []
      this.standardList = []
      this.cardInfo = {}
      this.form = {
        id: null,

        studentId: null,

        cardId: null,

        cardNo: null,

        count: null,

        giveCount: null,

        startTime: null,

        endTime: null,

        give: null,

        ascription: null,

        ascriptionSale: null,

        chargeAmount: null,

        charge: null,

        chargeNum: null,

        agreement: null,

        status: '0',

        type: null,

        createBy: null,

        createTime: null,

        updateBy: null,

        updateTime: null,

        remark: null,
      }
    },
    /** 新增按钮操作 */
    handleAdd(studentInfo,cardCount) {
      this.reset()
      this.formType = 1
      this.open = true
      this.formTitle = '添加'
      this.source = studentInfo.source
      this.form.studentId = studentInfo.id
      this.form.deptId = studentInfo.deptId
      if(cardCount == 0){
        this.form.ascriptionSale = studentInfo.ascriptionSale;
        this.ascriptionSaleDisabled = true;
      }
      this.cardSelect()
      this.getTreeSelect()
      this.getOwner()
      this.showFlag = true;
      this.balanceFlag = false;
    },
    /** 修改按钮操作 */
    handleUpdate(info, studentId, deptId) {
      this.reset()
      this.cardSelect()
      this.getOwner()
      this.getTreeSelect()
      this.formType = 2
      this.form.studentId = studentId
      getStudentCard(info.id, deptId).then((response) => {
        this.balanceFlag = true;
        this.form = response.data.studentCard
        this.form.tcardId = response.data.studentCard.cardId
        this.choseList = response.data.studentCard.choseList
        this.cardInfo.cardTypeName = response.data.card.cardTypeName
        this.cardInfo.count = response.data.card.count
        this.cardInfo.desc = response.data.card.desc
        this.cardInfo.flag = response.data.card.flag
        this.source = response.data.studentCard.source
        this.open = true
        this.formTitle = '修改'
        this.showFlag = this.currentDeptId == 100;
        this.ascriptionSaleDisabled = this.currentDeptId != 100;
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      if(this.form.cardType == 3){
        if(!this.form.time){
          this.$message.error('请填写私教卡有效期')
          return
        }if(!this.form.timeType){
          this.$message.error('请填写私教卡有效期类型')
          return
        }
      }

      this.form.source = this.source
      if(this.form.chargeAmount <= 0){
        this.$message.error('收费金额不能小于0')
        return
      }
      if (moment(this.form.chargeTime) >= moment(new Date())) {
        this.$message.error('收费时间不能大于当前时间！')
        return
      }
      this.spinning = true;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.choseList = this.choseList
          this.submitLoading = true
          if (this.form.id !== undefined && this.form.id !== null) {
            updateStudentCard(this.form)
              .then((response) => {
                this.$message.success('修改成功', 3)
                
                this.$emit('ok')
              })
              .finally(() => {
                this.submitLoading = false
                this.open = false
                this.spinning = false;
              })
          } else {
            addStudentCard(this.form)
              .then((response) => {
                this.$message.success('新增成功', 3)
                this.$emit('ok')
              })
              .finally(() => {
                this.submitLoading = false
                this.open = false
                this.spinning = false;
              })
          }
        } else {
          this.submitLoading = false
          this.spinning = false;
          return false
        }
      })
    },
  },
}
</script>
